package com.yuncheng.spcyApi.flow;

import cn.hutool.core.collection.CollectionUtil;
import com.yuncheng.spcyApi.vo.flow.SpcyJobXqVo;
import com.yuncheng.spcyApi.vo.jcy.JcyHpjlResVo;
import com.yuncheng.vo.HttpResult;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.busService.BusService;
import com.yuncheng.spcyApi.constant.flow.RckpConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.utils.DateConvert;
import com.yuncheng.spcyApi.utils.GetCurrentUserUtils;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import com.yuncheng.spcyApi.vo.flow.AgentVo;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.spcyApi.vo.common.Result;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 日常考评互评流程
 * @author hua
 */
@Component(value = "jcyRckpHpFlowService")
public class JcyRckpHpFlowService {

    private static final Logger log = LoggerFactory.getLogger(JcyRckpFlowService.class);

    @Resource
    @Lazy
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    @Resource
    @Lazy
    private ISpcyJcyRckphpjlService spcyJcyRckphpjlService;

    @Resource
    @Lazy
    private ISpcySqsxXpjlService spcySqsxXpjlService;

    @Resource
    @Lazy
    private BusService busService;

    @Resource
    @Lazy
    private ISpcySqsxJobService spcySqsxJobService;

    @Resource
    @Lazy
    private ISysFlowNodeService sysFlowNodeService;

    @Resource
    @Lazy
    private FlowNodeService flowNodeService;

    /**
     * 处理流程
     * @param flowVo 流程处理参数
     * @param jobId 流程任务id
     * @param pid 流程业务id
     * @param submitType 0: 保存；1: 提交
     * @param opinion 办理意见
     * @return
     */
    public Result handleFlow(FlowVo flowVo, String jobId, String pid, String submitType, String opinion){
        return this.handleFlow(flowVo, jobId, null, pid, submitType, opinion);
    }

    /**
     * 处理流程
     * @param nowJob 当前流程任务
     * @return
     */
    public Result handleFlow(FlowVo flowVo, String jobId, SpcySqsxJob nowJob, String pid, String submitType, String opinion){
        if (StringUtils.isBlank(jobId)){
            throw new BusinessException("流程任务id参数丢失！");
        }

        if (nowJob == null) {
            // 当前流程任务
            nowJob = spcySqsxJobService.getById(jobId);

            if (nowJob == null){
                return Result.error("当前流程任务不存在，请重试!");
            }
        }

        pid = nowJob.getFpid();
        if (StringUtils.isBlank(pid)){
            throw new BusinessException("业务参数为空！");
        }

        // 提交按钮
        if (submitType.equals(RckpConstant.SUBMIT_TYPE_SUBMIT)) {
            if (nowJob == null) {
                return Result.error("当前流程任务不存在");
            }
        }

        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            return Result.error("登录已失效，请重新登录");
        }

        if (StringUtils.isBlank(nowJob.getFhjmc())){
            throw new BusinessException("流程环节名称为空！");
        }

        // 流程环节处理
        Result httpResult = handleNodeName(flowVo, submitType, nowJob, pid, opinion);
        if (!httpResult.isSuccess()){
            return httpResult;
        }

        return Result.ok("操作成功");
    }

    /**
     * 流程环节处理
     * @param pid 业务id
     * @param flowVo 需要修改的字段内容
     * @param job 流程任务job
     * @param opinion 办理意见
     * @param submitType 提交、保存类型
     * @return true(),false(提示信息)
     */
    public Result handleNodeName(FlowVo flowVo,String submitType, SpcySqsxJob job, String pid, String opinion){
        HashMap<String, Object> map = flowVo.getMap();
        String smgflag = flowVo.getSmgflag(); // 短信发送标志
        String smsContent = flowVo.getSmsContent(); // 发送短信内容

        Result res = null;

        // 保存按钮
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SAVE)){

        }

        // 提交按钮
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SUBMIT)){

            if (job == null){
                throw new BusinessException("当前流程任务不存在！");
            }

            if (StringUtils.isBlank(job.getFhjmc())){
                throw new BusinessException("当前流程任务环节名称丢失！");
            }

            // 流程任务id
            String jobid = job.getId();

            // 提交流程任务,待办人是否为空，指定待办人
            if (StringUtils.isBlank(flowVo.getDbrid())) {
                // 按审查模式-提交-流程任务
                res = this.passJob(pid, jobid, job, opinion, flowVo.getNextNode(),flowVo.getNextNodeId(), null);
            }else {
                // 按审查模式-提交-流程任务
                res = this.passJob(pid, jobid, job, opinion, flowVo.getNextNode(),flowVo.getNextNodeId(),flowVo.getDbrid());
            }

            if (!res.isSuccess()){
                return res;
            }else {
                /**
                 * 接收返回的流程任务，如果返回的流程任务id不相等，发送短信
                 * 发送下环节短信
                 */
                if (StringUtils.isNotBlank(smgflag) && (smgflag.equals("是") || smgflag.equals("true"))){
                    busService.sendSmsToNextJob(jobid,smsContent);
                }
            }
        }

        return Result.ok("提交成功");
    }

    /**
     *  检查员互评一键优秀
     * @param id
     * @param pjrid 评价人id
     */
    public void jcyhpYjyx(String id, String pjrid){
        if (StringUtils.isBlank(id)){
            throw new BusinessException("业务参数为空！");
        }
        if (StringUtils.isBlank(pjrid)){
            throw new BusinessException("评价人为空！");
        }
        /*List<SpcyJcyRckphpjl> pjrList = spcyJcyRckphpjlService.selectPjrJcyHpList(sqsxid, pjrid, false);
        if (CollectionUtil.isEmpty(pjrList)){
            return;
        }*/
        SpcyJcyRckphpjl rckphpjl = spcyJcyRckphpjlService.getById(id);
        if (rckphpjl == null){
            throw new BusinessException("没有相匹配的数据！");
        }
        rckphpjl.setFljzlqk(SpcyConstant.XPJl_PJ_YX);
        rckphpjl.setFzdjcqd(SpcyConstant.XPJl_PJ_YX);
        rckphpjl.setFhdqxqk(SpcyConstant.XPJl_PJ_YX);
        rckphpjl.setFxcjcqxfj(SpcyConstant.XPJl_PJ_YX);
        rckphpjl.setFxcjczy(SpcyConstant.XPJl_PJ_YX);
        rckphpjl.setFzhpj(SpcyConstant.XPJl_PJ_YX);
        spcyJcyRckphpjlService.updateById(rckphpjl);


    }

    /**
     *  检查员互评一键优秀
     * @param id
     * @param pjrid 评价人id
     */
    public void jcyhpYjQk(String id, String pjrid){
        if (StringUtils.isBlank(id)){
            throw new BusinessException("业务参数为空！");
        }
        if (StringUtils.isBlank(pjrid)){
            throw new BusinessException("评价人为空！");
        }
        /*List<SpcyJcyRckphpjl> pjrList = spcyJcyRckphpjlService.selectPjrJcyHpList(sqsxid, pjrid, false);
        if (CollectionUtil.isEmpty(pjrList)){
            return;
        }*/
        SpcyJcyRckphpjl rckphpjl = spcyJcyRckphpjlService.getById(id);
        if (rckphpjl == null){
            throw new BusinessException("没有相匹配的数据！");
        }

        rckphpjl.setFljzlqk("");
        rckphpjl.setFzdjcqd("");
        rckphpjl.setFhdqxqk("");
        rckphpjl.setFxcjcqxfj("");
        rckphpjl.setFxcjczy("");
        rckphpjl.setFzhpj("");

        spcyJcyRckphpjlService.updateById(rckphpjl);
    }

    /**
     * 检查员互评-评价更新
     */
    public Result updateJcyhpPj(HashMap<String,String> buffer){
        String id = buffer.get("id");
        if (StringUtils.isBlank(id)){
            return Result.error("参数为空！");
        }
        SpcyJcyRckphpjl updateBean = spcyJcyRckphpjlService.getById(id);
        if (updateBean == null){
            return Result.error("没有相匹配的数据！");
        }

        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        try {
            BeanUtils.populate(updateBean, buffer);
        } catch (IllegalAccessException e) {
            log.error("修改申请检查项目出错-【IllegalAccessException】- {}",e.getMessage());
        } catch (InvocationTargetException e) {
            log.error("修改申请检查项目出错-【InvocationTargetException】",e.getMessage());
        }

        spcyJcyRckphpjlService.updateById(updateBean);

        return Result.ok();
    }

    /**
     * 查询评价人的检查员互评记录
     * @param sqsxid 申请事项id
     * @param pjrid 评价人id
     */
    public List<SpcyJcyRckphpjl> queryPjrJcyHpjlList(String sqsxid, String pjrid){
        return spcyJcyRckphpjlService.selectPjrJcyHpList(sqsxid, pjrid, true);
    }

    /**
     * 查询被评价人的检查员互评记录-根据评价人id
     * @param sqsxid 申请事项id
     * @param pjrid 评价人id
     */
    public List<JcyHpjlResVo> queryBprListByPjrId(String sqsxid, String pjrid){
        return spcyJcyRckphpjlService.selectBprListByPjrId(sqsxid, pjrid);
    }

    /**
     * 查询所有的检查员互评记录
     */
    public List<Map> queryAllJcyHpjlListOld(String sqsxid){
        Map resultMap = new HashMap();

        List<SpcyJcyRckphpjl> allHpList = spcyJcyRckphpjlService.queryAllJcyHpjlList(sqsxid);

        List<Map> resultMapList = new ArrayList<>();
        List<String> pjrIdList = new ArrayList<>(allHpList.size()); // 评价人idList
        for (int i = 0; i < allHpList.size(); i++) {
            String fpjrid = allHpList.get(i).getFpjrid();
            if (StringUtils.isBlank(fpjrid) || pjrIdList.contains(fpjrid)){
                continue;
            }
            pjrIdList.add(fpjrid);
            String fpjrxm = allHpList.get(i).getFpjrxm();
            String fpjrzg = allHpList.get(i).getFpjrzg();

            // 被评价人列表
            List<SpcyJcyRckphpjl> bpjrList = allHpList.stream()
                    .filter(f -> StringUtils.isNotBlank(f.getFpjrid()) && f.getFpjrid().equals(fpjrid))
                    .collect(Collectors.toList());

            Map dataMap = new HashMap();
            dataMap.put("fpjrxm", fpjrxm); // 评价人姓名
            dataMap.put("fpjrzg", fpjrzg); // 评价人资格
            dataMap.put("bpjList", bpjrList); // 被评价人列表
            resultMapList.add(dataMap);

        }
        return resultMapList;
    }

    public List<Map> queryAllJcyHpjlListNew(String sqsxid){
        Map resultMap = new HashMap();

        List<SpcyJcyRckphpjl> allHpList = spcyJcyRckphpjlService.queryAllJcyHpjlList(sqsxid);

        List<Map> resultMapList = new ArrayList<>();
        List<String> pjrIdList = new ArrayList<>(allHpList.size()); // 评价人idList
        for (int i = 0; i < allHpList.size(); i++) {
            String fpjrid = allHpList.get(i).getFbpjrid();
            if (StringUtils.isBlank(fpjrid) || pjrIdList.contains(fpjrid)){
                continue;
            }
            pjrIdList.add(fpjrid);
            String fpjrxm = allHpList.get(i).getFbpjrxm();
            String fpjrzg = allHpList.get(i).getFbpjrzg();

            // 被评价人列表
            List<SpcyJcyRckphpjl> bpjrList = allHpList.stream()
                    .filter(f -> StringUtils.isNotBlank(f.getFbpjrid()) && f.getFbpjrid().equals(fpjrid))
                    .collect(Collectors.toList());

            Map dataMap = new HashMap();
            dataMap.put("fpjrxm", fpjrxm); // 评价人姓名
            dataMap.put("fpjrzg", fpjrzg); // 评价人资格
            dataMap.put("bpjList", bpjrList); // 被评价人列表
            resultMapList.add(dataMap);

        }
        return resultMapList;
    }

    /**
     * 同步移除检查员互评
     */
    public void syncDelRckpHpFlow(String sqsxid, String fuserid){
        // 删除评价人记录
        spcyJcyRckphpjlService.remove(new LambdaQueryWrapper<SpcyJcyRckphpjl>()
                .eq(SpcyJcyRckphpjl::getFsqsxid, sqsxid)
                .eq(SpcyJcyRckphpjl::getFpjrid, fuserid));

        // 删除流程待办
        spcySqsxJobService.remove(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, sqsxid)
                .eq(SpcySqsxJob::getFdbrid, fuserid)
                .like(SpcySqsxJob::getFlcmc, SpcyFlowConstant.RCKPHP_LCMC)
        );

    }

    /**
     * 初始化检查员互评
     * @param sqsxid 申请事项id
     */
//    @Async(value = "asyncNormalTask")
    public void initRckpHpFlow(String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            return;
        }

        // 正式检查员选派列表
        List<SpcySqsxXpjl> zsjcyXpList = spcySqsxXpjlService.getTyXpXpjlZsjcyList(sqsxid);

        if (CollectionUtil.isEmpty(zsjcyXpList)){
            return;
        }

        List<String> dbrIdList = new ArrayList<>(zsjcyXpList.size()+1); // 待办人id列表

        // 生成对应的检查员互评列表
        for (int i = 0; i < zsjcyXpList.size(); i++) {
            if (StringUtils.isBlank(zsjcyXpList.get(i).getFuserid())){
                continue;
            }
            String pjrid = zsjcyXpList.get(i).getFuserid();
            String pjrxm = zsjcyXpList.get(i).getFjcyxm();
            String pjrzg = zsjcyXpList.get(i).getFssk();

            // 被评价人列表
            List<SpcySqsxXpjl> bpjrList = zsjcyXpList.stream()
                    .filter(f -> StringUtils.isNotBlank(f.getFuserid()) && !f.getFuserid().equals(pjrid))
                    .collect(Collectors.toList());

            for (int p = 0; p < bpjrList.size(); p++){
                // 对应互评记录是否存在
                List<SpcyJcyRckphpjl> pjrhpList = spcyJcyRckphpjlService.list(new LambdaQueryWrapper<SpcyJcyRckphpjl>()
                        .eq(SpcyJcyRckphpjl::getFpjrid, pjrid)
                        .eq(SpcyJcyRckphpjl::getFbpjrid, bpjrList.get(p).getFuserid())
                        .eq(SpcyJcyRckphpjl::getFsqsxid, sqsxid));
                if (CollectionUtil.isNotEmpty(pjrhpList)){
                    continue;
                }

                SpcyJcyRckphpjl rckphpjl = new SpcyJcyRckphpjl();
                rckphpjl.setId(GetUuIdUtils.ReplaceUuId());
                rckphpjl.setFsqsxid(sqsxid);

                rckphpjl.setFpjrid(pjrid);
                rckphpjl.setFpjrxm(pjrxm);
                rckphpjl.setFpjrzg(pjrzg);

                rckphpjl.setFbpjrid(bpjrList.get(p).getFuserid());
                rckphpjl.setFbpjrxm(bpjrList.get(p).getFjcyxm());
                rckphpjl.setFbpjrzg(bpjrList.get(p).getFssk());
                rckphpjl.setFtjzt("0");
                spcyJcyRckphpjlService.save(rckphpjl);
            }
            dbrIdList.add(pjrid);
        }

        // 初始化流程
        for (int i = 0; i<dbrIdList.size(); i++) {
            try {
                initJob(sqsxid, dbrIdList.get(i), GetCurrentUserUtils.getCurrentUser());
            }catch (Exception e){
                log.error("初始化检查员互评流程-错误：{}", e.getMessage());
            }
        }
    }

    /**
     * 初始化流程
     * @param pid 业务id
     * @param dbrId 待办人id
     * @param currentUser 当前登陆用户
     * @return
     */
    public Result initJob(String pid, String dbrId, CurrentUserVo currentUser){
        return this.initJob(pid, dbrId, currentUser, false);
    }

    /**
     * 初始化流程
     * @param pid 业务id
     * @param currentUser 当前登陆用户
     * @param isSendSms 是否发送短信
     * @return
     */
    public Result initJob(String pid, String dbrId, CurrentUserVo currentUser, boolean isSendSms){
        String lcmbCode = SpcyFlowConstant.KP_RCKHHP_FLOW_CODE;

        //获取流程模板的第一个环节
        SysFlowTemple code = sysFlowNodeService.getCode(lcmbCode);

        List<SysFlowNode> node = sysFlowNodeService.getFirstNode(code.getId());

        LambdaQueryWrapper<SpcySqsxJob> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpcySqsxJob::getFpid, pid);
        queryWrapper.eq(SpcySqsxJob::getFnodeid, node.get(0).getId());
        queryWrapper.eq(StringUtils.isNotBlank(dbrId), SpcySqsxJob::getFdbrid, dbrId);

        List<SpcySqsxJob> jobList = spcySqsxJobService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(jobList)){
            return Result.error("当前申请事项环节["+node.get(0).getFjdmc()+"】已经初始化了!");
        }

        Result result = flowNodeService.createJob(lcmbCode, pid, dbrId, node.get(0),null,null,currentUser);
        if (!result.isSuccess()){
            return result;
        }else {
            if (isSendSms) {
                SpcySqsxJob job = (SpcySqsxJob) result.getResult();
                if (job != null) {
                    String nextNodeSmsContent = busService.getNextNodeSmsContent(job, null);
                    busService.sendSmsToNodeDbr(job.getFdbrid(), job.getFlcmc() + "-" + job.getFhjmc(), nextNodeSmsContent);
                }
            }
        }

        return result;
    }


    /**
     * 提交流程
     * @param pid 业务id
     * @param jobid 流程任务id
     * @param job 当前流程任务
     * @param opinion 办理意见
     * @param nextNodeName 下环节结点名称
     * @param nextNodeId 下环节结点id
     * @param nextNodeDbrIds 下环节待办人
     * @return
     */
    private Result passJob(String pid,String jobid,SpcySqsxJob job, String opinion,String nextNodeName,String nextNodeId,String nextNodeDbrIds){
        if (job == null){
            job = spcySqsxJobService.getById(jobid);
        }
        String jobNodeName = job.getFhjmc(); // 当前环节名称

        Result httpResult = null;

        // 是否为最终结点
        if (StringUtils.isNotBlank(jobNodeName) && jobNodeName.equals(SpcyFlowConstant.RCKPHP_HJMC_END)){
            //办理掉当前环节
            httpResult = flowNodeService.doJob(job, opinion);
        }else {
            httpResult = flowNodeService.passJob(SpcyFlowConstant.KP_RCKHHP_FLOW_CODE, pid, jobid, opinion, nextNodeId, nextNodeDbrIds);
        }

        if (!httpResult.isSuccess()){
            return httpResult;
        }

        return Result.ok("success");
    }

    /**
     * 白名单-检查员日常互评流程提交
     * */
    public HttpResult whiteSubmitJob(FlowVo flowVo){
        if (StringUtils.isBlank(flowVo.getJobid())){
            return HttpResult.error("流程参数为空！");
        }
        if (StringUtils.isBlank(flowVo.getOpinion())){
            flowVo.setOpinion("同意");
        }
        SpcySqsxJob nowJob = spcySqsxJobService.getById(flowVo.getJobid());
        if (nowJob == null){
            return HttpResult.error("没有相匹配的流程数据！");
        }

        Result result = flowNodeService.bjCommonJob(flowVo.getJobid(), nowJob, flowVo.getOpinion());
        if (!result.isSuccess()){
            return HttpResult.error(result.getMessage());
        }

        return HttpResult.ok("提交成功");
    }

    /**
     * 获取当前流程任务相关信息
     * @param jobid 流程任务id
     */
    public Map getJobConcernByJobId(String jobid){
        return getJobConcernByJobId(jobid, null);
    }

    /**
     * 获取当前流程任务相关信息
     * @param jobid 流程任务id
     */
    public Map getJobConcernByJobId(String jobid, SpcySqsxJob job){
        Map map = new HashMap();

        // 当前流转记录
        if (job == null) {
            job = spcySqsxJobService.getById(jobid);
            if (job == null) {
                log.error("当前流程任务id为【{}】的流转记录不存在", jobid);
                throw new BusinessException("流程任务不存在！");
            }
        }

        String sqsxid = job.getFpid();
        if (org.apache.commons.lang3.StringUtils.isBlank(sqsxid)){
            log.error("当前流程任务id为【{}】的流转记录中的申请事项id为空",jobid);
            throw new BusinessException("业务参数为空!");
        }

        // 申请事项基本信息
        SpcySqsxBasic sqsxBasic = spcySqsxBaiscService.getById(sqsxid);

        // 流程任务流传记录
        /*LambdaQueryWrapper<SpcySqsxJob> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpcySqsxJob::getFpid, sqsxid);
        queryWrapper.like(SpcySqsxJob::getFlcmc, SpcyFlowConstant.RCKP_LCMC);
        queryWrapper.orderByAsc(SpcySqsxJob::getFfssj);
        queryWrapper.orderByAsc(SpcySqsxJob::getCreateTime);
        List<SpcySqsxJob> jobList = spcySqsxJobService.list(queryWrapper);*/

        map.put("sqsx", sqsxBasic); // 申请事项基本信息
        map.put("job", job); // 当前流转记录
        map.put("jobHistoryList", spcySqsxJobService.selectHistoryListByFpidAndFlcmc(sqsxid, SpcyFlowConstant.RCKP_LCMC)); // 流程任务流传记录

        // 获取下环节待办人
        map.putAll(this.getNextNodeDbr(jobid, job));

        return map;
    }

    /**
     * 获取APP-获取当前流程任务相关信息
     */
    public Map getAppJobConcernByJobId(String jobid, SpcyJobXqVo job){
        Map map = new HashMap();

        if (job == null) {
            job = spcySqsxJobService.selectJobInfoById(jobid);
            if (job == null) {
                throw new BusinessException("当前流程任务不存在！");
            }
        }
        SpcySqsxBasic sqsx = spcySqsxBaiscService.selectSqsxInfoById(job.getFpid());

        map.put("sqsx", sqsx); // 申请事项基本信息
        map.put("job", job); // 当前流转记录
        return map;
    }

    /**
     * 获取下环节待办人
     * @param jobid
     * @param job
     * @return
     */
    private Map getNextNodeDbr(String jobid,SpcySqsxJob job){
        Map map = new HashMap();

        Map nextDbr = this.getNowJobInNextDbrAndHandlePageUrl(jobid, job);
        String nextNodeId = ""; // 下结点id
        String nextNode = "办结"; // 下结点名称
        if (nextDbr.get("nextNode") != null) {
            SysFlowNode nextFlowNode = (SysFlowNode) nextDbr.get("nextNode");
            nextNodeId = nextFlowNode.getId();
            nextNode = nextFlowNode.getFjdmc();
        }
        List<AgentVo> dbrListByMap = this.getDbrListByMap(nextDbr);

        map.put("nextNodeDbrList", dbrListByMap); // 下环节待办人list

        map.put("nextNode", nextNode); // 下流程结点名称
        map.put("nextNodeId", nextNodeId); // 下流程结点id

        return map;
    }

    /**
     * 获取下一个环节名称和待办人
     * @param job 流程任务
     * @param jobid 流程任务id
     * @return
     * {
     *     dbrId
     *     dbr:
     *     nextNode：下流程结点
     *     handlePageUrl：办理页面路径
     * }
     */
    private Map getNowJobInNextDbrAndHandlePageUrl(String jobid, SpcySqsxJob job){
        if (job == null && StringUtils.isNotBlank(jobid)){
            job = spcySqsxJobService.getById(jobid);
        }
        String flowCode = SpcyFlowConstant.KP_RCKHHP_FLOW_CODE;
        return flowNodeService.getNowJobInNextDbrAndHandlePageUrl(flowCode, job, null);
    }

    /**
     * 将待办人map转为List
     * @param map { dbrId: 待办人id ; dbr: 待办人 }
     */
    private List<AgentVo> getDbrListByMap(Map map){
        String dbrids = map.get("dbrId").toString(); // 待办人id
        String dbrs = map.get("dbr").toString(); // 待办人

        List<AgentVo> agentList = new ArrayList<>();

        if (StringUtils.isNotBlank(dbrids)) {
            String agentIds[] = dbrids.split(",|，");
            String agentNames[] = dbrs.split(",|，");

            for (int i = 0; i < agentIds.length; i++) {
                AgentVo agentVo = new AgentVo();
                agentVo.setDbrid(agentIds[i]);
                agentVo.setDbr(agentNames[i]);
                agentList.add(agentVo);
            }
        }

        return agentList;
    }

    /**
     * 获取当前环节待办人
     * @param pid 业务id
     * @param nodeName 环节名称
     * @return
     */
    public Map getNodeDbr(String pid, String nodeName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";

        /*SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(pid);
        String dept = "";
        if (sqsx != null && StringUtils.isNotBlank(sqsx.getFywflcode())){
            dept = SpcyConstant.getYwclNameByCode(sqsx.getFywflcode());
        }*/

        if (nodeName.equals(SpcyFlowConstant.RCKPHP_HJMC_JBRSH)){
            Map xcjcMap = getXcjcRyBySqsxId(pid, SpcyConstant.FLOW_TYPE_CY);
            dbrId = xcjcMap.get("dbrId").toString();
            dbr = xcjcMap.get("dbr").toString();
        }


        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    /**
     * 获取现场检查人员
     * @param sqsxId 申请事项id
     * @param flowType 查验/审评
     */
    private Map getXcjcRyBySqsxId(String sqsxId,String flowType){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";

        // 同意选派记录
        List<SpcySqsxXpjl> xpjlList = spcySqsxXpjlService.getTyXpXpjlList(sqsxId, flowType);
        if (CollectionUtils.isNotEmpty(xpjlList)){
            for (SpcySqsxXpjl xpjl : xpjlList){
                if (StringUtils.isBlank(dbrId)){
                    dbrId += xpjl.getFuserid();
                    dbr += xpjl.getFjcyxm() + "(" + Optional.ofNullable(xpjl.getFssk()).orElseGet(() -> "组员") + ")";
                }else {
                    dbrId += "," + xpjl.getFuserid();
                    dbr += "," + xpjl.getFjcyxm() + "(" + Optional.ofNullable(xpjl.getFssk()).orElseGet(() -> "组员") + ")";
                }
            }
        }

        map.put("dbrId", dbrId);
        map.put("dbr", dbr);
        return map;
    }
}
